/*
 * Copyright (c) 2012 Universidad Antonio de Nebrija.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Apache License v2.0
 * which accompanies this distribution, and is available at
 * http://www.apache.org/licenses/LICENSE-2.0.html
 * 
 * Contributors:
 *    Universidad Antonio de Nebrija - initial API, implementation and documentation
 */
package com.nebrija.riif.cli;

import java.util.ArrayList;
import java.util.StringTokenizer;

import com.nebrija.riif.model.Environment;
import com.nebrija.riif.model.RIIFElement;
import com.nebrija.riif.model.RIIFProperties;
import com.nebrija.riif.model.RootClass;

/**
 * Command to clear the calculation of property values
 * @author asanchep
 *
 */
public class ListCommand implements Command {

	@Override
	public String execute(ArrayList<String> params) throws CommandException {
		RIIFElement queried = RootClass.getInstance();
		String name = queried.getName();
		if(params.size()>0){
			name=params.get(0);
			StringTokenizer stk = new StringTokenizer(params.get(0),"'");
			while (stk.hasMoreTokens()){
				String subelement = stk.nextToken();
				queried = queried.getElement(subelement);
				if(queried==null){
					throw new CommandException(CommandException.ELEMENT_NOT_FOUND);
				}
				if(queried instanceof RIIFProperties){
					return queried.toString();
				}
			}
		}
		return list (queried, name);
	}
	
	public String list (RIIFElement main, String name){
		StringBuffer sb = new StringBuffer("Elements for ");
		sb.append(name).append(": ");
		sb.append(main.getChildCount());
		for(String elementName: main.getElementNames()){
			RIIFElement element = main.getElement(elementName);
			sb.append("\n").append(elementName).append(" - ").append(element.getClass().getSimpleName());
			if (element instanceof Environment && element==RootClass.getInstance().getActiveEnvironment()){
				sb.append(" (active) ");
			}
		}
		return sb.toString();		
	}

	@Override
	public String helpString() throws CommandException {
		return ": lists all the elements available at the ROOT level";
	}

}
